iT邦幫忙

2025 iThome 鐵人賽

DAY 21
0
Vue.js

邊學邊做:Vue.js 實戰養成計畫系列 第 21

Day 21:共享能量池 — 跨元件資料共享(store 實作)

  • 分享至 

  • xImage
  •  

今天要學什麼?
1.多個元件取用同一個 store
→ 例如星艦的「燃料」狀態,在駕駛艙顯示剩餘量,在維修艙也能操作加油。

2.修改資料的影響是同步的
→ 任何一個元件呼叫 actions 改變 state,其他地方會即時反映。

3.模擬小專案
→ 做一個「燃料共享」範例,三個元件共用同一池能量。

Store 的核心概念

  • state:存放共享的資料(能量槽)。
  • actions:定義如何修改資料(加油、消耗燃料)。
  • getters:從資料衍生出新的結果(剩餘比例、是否需要維修)。

跨元件如何使用?

1.建立 store → 用 defineStore 定義一個能量核心。
2.在任意元件呼叫 useXxxStore() → 直接拿到 state、actions、getters。
3.即時同步 → 一個元件修改,所有元件都跟著更新。

實作

今天的「共享能量池」實作,我們要沿用Day 20 的程式碼來擴充!實際玩一個「跨元件共享」的範例。
重點是:學會怎麼在不同元件間共用同一個 store 的資料,不需要 props 傳來傳去。

1. 建立 store:src/stores/planet.js

import { defineStore } from 'pinia'

export const useShipStore = defineStore('ship', {
  state: () => ({
    fuel: 100
  }),
  actions: {
    consume(amount) {
      if (this.fuel >= amount) this.fuel -= amount
    },
    refill() {
      this.fuel = 100
    }
  }
})

2. 駕駛艙元件(src/components/Cockpit.vue

<template>
  <div>
    <h2>🚀 駕駛艙</h2>
    <p>剩餘燃料:{{ ship.fuel }}</p>
    <button @click="ship.consume(10)">航行消耗 10</button>
  </div>
</template>

<script setup>
import { useShipStore } from '../stores/ship'
const ship = useShipStore()
</script>

3. 維修艙元件(src/components/EngineRoom.vue

<template>
  <div>
    <h2>🔧 維修艙</h2>
    <p>燃料狀態:{{ ship.fuel }}</p>
    <button @click="ship.refill">加滿燃料</button>
  </div>
</template>

<script setup>
import { useShipStore } from '../stores/ship'
const ship = useShipStore()
</script>

4. 儀表板元件(src/components/Dashboard.vue

<template>
  <div>
    <h2>📊 儀表板</h2>
    <progress :value="ship.fuel" max="100"></progress>
    <span>{{ ship.fuel }} / 100</span>
  </div>
</template>

<script setup>
import { useShipStore } from '../stores/ship'
const ship = useShipStore()
</script>

5. 在 App.vue 引入 <Cockpit /><EngineRoom /><Dashboard />

<template>
  <main>
    <Cockpit />
    <EngineRoom />
    <Dashboard />
  </main>
</template>

<script setup>
import Cockpit from './components/Cockpit.vue'
import EngineRoom from './components/EngineRoom.vue'
import Dashboard from './components/Dashboard.vue'
</script>

結果

到這裡,你的「星艦能量池」就能讓駕駛艙、維修艙、儀表板共用同一份燃料數據。
重點差異:以前每個頁面自己處理資料,現在全部交給 Pinia 管理,真正做到「跨元件共享」。

參考資源
https://vuejs.org/guide
https://www.runoob.com/vue3


上一篇
Day 20:能量核心 — Pinia 狀態管理基礎
下一篇
Day 22:與外星文明溝通 — Axios
系列文
邊學邊做:Vue.js 實戰養成計畫26
圖片
  熱門推薦
圖片
{{ item.channelVendor }} | {{ item.webinarstarted }} |
{{ formatDate(item.duration) }}
直播中

尚未有邦友留言

立即登入留言